package com.llc.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.llc.common.to.OrderLockStockTO;
import com.llc.common.to.SkuStockTO;
import com.llc.common.to.mq.OrderTo;
import com.llc.common.to.mq.StockDetailTo;
import com.llc.common.to.mq.StockLockedTo;
import com.llc.common.utils.R;
import com.llc.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.llc.gulimall.ware.entity.WareOrderTaskEntity;
import com.llc.gulimall.ware.exception.NoStockException;
import com.llc.gulimall.ware.feign.OrderFeignService;
import com.llc.gulimall.ware.feign.ProductFeignService;
import com.llc.gulimall.ware.service.WareOrderTaskDetailService;
import com.llc.gulimall.ware.service.WareOrderTaskService;
import com.llc.gulimall.ware.vo.*;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llc.common.utils.PageUtils;
import com.llc.common.utils.Query;

import com.llc.gulimall.ware.dao.WareSkuDao;
import com.llc.gulimall.ware.entity.WareSkuEntity;
import com.llc.gulimall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

//@RabbitListener(queues = "stock.release.stock.queue")
@Slf4j
@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;

    @Autowired
    OrderFeignService orderFeignService;

    //处理消息方法,库存自动解锁
    /**
     *
     * @author llc
     * @description //处理消息方法,库存自动解锁
     * @date 2022/2/17 18:59
     * @param to
     * @param message
     * @return void
     */

    /*@RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息：");
        //库存工作单id
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();
        //解锁库存
        //查订单对应库存信息
        //有 库存锁定成功
        //无，不需要解锁,库存锁定失败回滚了。
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if(byId != null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0){
                //订单数据返回成功
                OrderVo data = (OrderVo) r.getData(new TypeReference<OrderVo>() {
                });
                if(data == null || data.getStatus() == 4){
                    //订单不存在
                    //订单被取消。
                    unlockedStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }

            }else {
                //消息拒绝后重新返回队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }
        }
        else{
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            //不解锁
        }
    }*/

    /**
     *
     * @author llc
     * @description 解锁订单方法
     * @date 2022/2/17 19:33
     * @param
     * @return void
     */

    private void unlockedStock(Long skuId, Long wareId, Integer num, Long taskDetailId){
        //库存解锁
        wareSkuDao.unlockStock(skuId,wareId,num);
        //订单也调整为解锁状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);
        orderTaskDetailService.updateById(entity);
    }


    /**
     * 为某订单锁库存
     * 下订单成功，未支付，被取消 系统取消或用户
     * 下订单成功，业务调用失败 回滚
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //保存库存工作单
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        System.out.println("保存库存工作单");
        orderTaskService.save(taskEntity);
        System.out.println("保存完成");

        //找到每个商品在哪个仓库有库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询商品总库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());
        // 锁定库存
        for(SkuWareHasStock hasStock : collect){
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if(wareIds == null || wareIds.size() == 0){
                //没有任何仓库有商品
                throw new NoStockException(skuId);
            }
            // 成功就将记录发送给mq
            // 锁定失败，则给工作单就回滚。如果没有id 则查不到id。
            for(Long wareId : wareIds){
                //成功返回1  否则是0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if(count  == 1){
                    skuStocked = true;
                    //todo 发消息告诉mq库存锁定成功
                    WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity(null,skuId,"",hasStock.getNum(),taskEntity.getId(),
                            wareId,1);
                    orderTaskDetailService.save(entity);
                    System.out.println("");
                    StockLockedTo lockedTo = new StockLockedTo();
                    //保存工作单id
                    lockedTo.setId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(entity,stockDetailTo);
                    //只发id不行，防止回滚找不到数据
                    lockedTo.setDetailTo(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",lockedTo);
                    System.out.println("消息发送成功");
                    break;
                } else {
                    //当前仓库锁失败,重试下一个仓库
                }
            }
            if(skuStocked == false){
                //当前所有仓库都没锁住
                throw new NoStockException(skuId);
            }
        }
        //3 肯定全部都是锁定成功的
        return true;
    }

    /**
     *
     * @author llc
     * @description  防止订单卡顿
     * @date 2022/2/18 1:43
     * @param orderTo
     * @return void
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        //查一下最新状态，防止重复解锁
        log.info("查询订单最新状态");
        WareOrderTaskEntity task  =  orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = task.getId();
        log.info("获取订单的id"+id);
        //按工作单找解锁的库存
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", id)
                .eq("lock_status", 1)
        );

        //Long skuId, Long wareId, Integer num, Long taskDetailId
        for (WareOrderTaskDetailEntity entity : entities) {
            //解锁订单
            unlockedStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getId());
        }
        log.info("解锁成功");
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        //库存工作单id
        StockDetailTo detail = to.getDetailTo();
        Long detailId = detail.getId();
        //解锁库存
        //查订单对应库存信息
        //有 库存锁定成功
        //无，不需要解锁,库存锁定失败回滚了。
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if(byId != null){
            //解锁
            Long id = to.getId();
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            //根据订单号查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if(r.getCode() == 0){
                //订单数据返回成功
                OrderVo data = (OrderVo) r.getData(new TypeReference<OrderVo>() {
                });
                if(data == null || data.getStatus() == 4){
                    //订单不存在
                    //订单被取消。
                    if(byId.getLockStatus() == 1){
                    unlockedStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);}
                    //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }

            }else {
                throw  new RuntimeException("远程服务失败");
                //消息拒绝后重新返回队列
                //channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }
        }
        else{
            //channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            //不解锁
        }
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * skuId: 1
         * wareId: 2
         */
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }


        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录新增
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if(entities == null || entities.size() == 0){
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setSkuId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);
            //TODO 远程查询sku的名字，如果失败，整个事务无需回滚
            //1、自己catch异常
            //TODO 还可以用什么办法让异常出现以后不回滚？高级
            try {
                R info = productFeignService.info(skuId);
                Map<String,Object> data = (Map<String, Object>) info.get("skuInfo");

                if(info.getCode() == 0){
                    skuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }
            wareSkuDao.insert(skuEntity);
        }else{
            wareSkuDao.addStock(skuId,wareId,skuNum);
        }
    }

    /**
     *
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        return skuIds.stream().map(skuId -> {
            /**
             *  查询语句
             *  select  SUM(stock -stock_locked) FROM `wms_ware_sku` where sku_id=1
             */
            Long count = this.baseMapper.getSkuStock(skuId);
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(count == null?false:count > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
    }



    @Override
    public List<SkuStockTO> getSkusStock(List<Long> skuIds) {
        List<SkuStockTO> collect = skuIds.stream().map(skuId -> {
            SkuStockTO skuStockTO = new SkuStockTO();
            Long stock = baseMapper.getSkuStock(skuId);
            skuStockTO.setSkuId(skuId);
            skuStockTO.setStock(stock == null ? 0 : stock);
            return skuStockTO;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public Long getSkuStock(Long skuId) {
        return baseMapper.getSkuStock(skuId);
    }

}